<?php
class helper_language extends system_view_helper_abstract {
	
	protected $_coreLoaded = false;
	protected $_language = array();
	protected $_import = array();
	protected $_name = 'en_US';
	protected $_dir = _DIRECTORY_APP;
	
	public function __construct() {
		parent::__construct();
		$this->init();
	}
	
	/**
	 * @return helper_language
	 */
	public function init() {
		$template = system_view_abstract::getTemplate();
		if($template !== null) $template .= DIRECTORY_SEPARATOR;
		$this->_dir = _DIRECTORY_APP . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR . $template;
		$this->_name = system_passport::getInstance()->getInstance()->getStorage()->getLanguage();
		return $this;
	}
	
	public function __toString() {
		return $this->_name;
	}
	
	/**
	 * @return helper_language
	 */
	public function reload() {
		$this->init();
		$this->_coreLoaded = false;
		$this->_import = array();
		$this->_language = array();
		return $this->language();
	}
	
	/**
	 * @return helper_language
	 */
	public function language() {
		if($this->_coreLoaded === false) {
			$vid = explode('-', $this->getView()->viewId());
			$this->import()->import($vid[0]);
			$this->_coreLoaded = true;
		}
		return $this;
	}
	
	/**
	 * @return helper_language
	 */
	public function import($index = '') {		
		if(!in_array($index, $this->_import)) {
			if($index=='') {
				$filename = $this->_dir . $this->_name . '.php';
			} else {
				$filename = $this->_dir . $this->_name . DIRECTORY_SEPARATOR . $index . '.php';
			}
			if(file_exists($filename)) {
				$new = include($filename);
				if(is_array($new)) {
					$new = array_change_key_case($new, CASE_LOWER);
					$this->_language = array_merge($this->_language, $new);
				}
			}
			$this->_import[] = $index;
		}
		return $this;
	}
	
	public function __call($method, array $args) {
		if(preg_match('/^get(\w+?)$/', $method, $matches)) {
			return $this->load($matches[1], '');
		}
		return null;
	}
	
	public function load($index) {
		$glue = $this->_name == 'en_US' ? ' ' : '';
		if(is_string($index)) {		
			$name = trim(strtolower($index));
			if(isset($this->_language[$name])) {
				return $this->_language[$name];
			} else {
				$index = explode(' ', $index);
			}
		}
		if(is_array($index)) {
			if(empty($index)) return '';
			$result = array();
			foreach($index AS $value) {
				$key = trim(strtolower($value));
				$result[] = isset($this->_language[$key]) ? $this->_language[$key] : $value;
			}
			return implode($glue, $result);
		}
		return (string) $index;
	}

}